<template>
    <view style="height: 100vh; position: relative" class="flex flex-column">
        <view style="position: absolute; height: 40vh; width: 100vw; background: #000; z-index: 1;">
        </view>
        <view
            :style="{ position: 'absolute', marginTop: menuButtonInfo.top + 'px', zIndex: 2, left: 40 + 'rpx', paddingTop: 12 + 'rpx' }">
            <u-icon name="arrow-left" color="#fff" size="36rpx" @click="() => { goBack(); }"></u-icon>
        </view>
        <video object-fit="cover" id="myVideo" style="width: 100vw; z-index: 1; height: 32vh;" :src="playData.playUrl"
            @timeupdate="bindtimeupdate" @pause="() => {
                onPause(() => { })
            }" @ended="() => {
                onPause(() => {
                })
            }" @play="onPlay"></video>
        <view style="height: 68vh; margin-top: -1vh; z-index: 3;  display: flex; flex-direction: column;">
            <view style="padding: 40rpx;background-color: #fff;border-radius: 5vh 5vh 0 0;">
                <view style="display: flex;justify-content: space-between;">
                    <view>{{ queryData.name }}</view>
                    <view style="display: flex;align-items: center;">
                        <image src="../../static/images/pratice.svg"
                            style="width: 36rpx;height: 36rpx;margin-right: 15rpx;" />
                        <view @click="onStartPractice" style="text-decoration: underline;">试题练习</view>
                    </view>
                </view>
                <view style="margin: 30rpx 0;display: flex;align-items: center;justify-content: space-between;">
                    <view style="display: flex; align-items: center;">
                        <image
                            :src="Object.keys(loginData).length === 0 ? '../../static/images/smallTx.svg' : loginData.avatar"
                            style="width:50rpx;height:50rpx;border-radius:50%;margin-right: 20rpx;" />
                        {{ loginData.nickName }}
                    </view>
                    <view style="display: flex; align-items: center;">
                        <image src="../../static/images/time.svg"
                            style="width:50rpx;height:50rpx;margin-right: 20rpx;" />
                        <!-- {{ playData.time }}分钟 -->
                        {{ ((playData.time || 0) / 60).toFixed(1) }}分钟
                    </view>
                    <view style="display: flex; align-items: center;">
                        <image src="../../static/images/takePart.svg"
                            style="width:50rpx;height:50rpx;margin-right: 20rpx;" />
                        参与学习{{ studyNum }}人
                    </view>
                </view>
                <view style="width: 100%;height: 1px;background-color: #EEEEEE;"></view>
                <view style="margin: 60rpx 0;">
                    <view style="text-align: center;margin-bottom: 30rpx;">课件简介</view>
                    <view style="color: #666666;font-size: 14px;">
                        {{ playData.lectureNotes }}
                    </view>
                </view>
                <view style="position: relative;">
                    <view
                        style="box-shadow: 2px 4px 10px 0px #0000001F;background-color: #F8FFF9;padding: 40rpx;margin-top: 40rpx;">
                        <image src="../../static/images/leftIcon.svg"
                            style="width: 144rpx;height: 138rpx;position: absolute;left: -34rpx;top: -40rpx;" />
                        <view style="text-align: center;margin-bottom: 30rpx;">我的笔记</view>

                        <view>
                            <view v-for="(item, index) in note" :key="item.id"
                                style="display: flex;justify-content: space-between;margin-bottom: 60rpx">
                                <view style="font-size: 26px;color: #37B874;width: 5%;">
                                    {{ index + 1 }}
                                </view>
                                <view style="width: 90%;">
                                    <view>{{ item.notesContent }}</view>
                                    <view style="display: flex;justify-content: space-between;margin-top: 30rpx;">
                                        <view style="display: flex;align-items: center;color: #666666"
                                            @click="onClickSeek(item.learningTime)">
                                            <image src="../../static/images/play.svg"
                                                style="width: 40rpx;height: 40rpx;margin-right: 20rpx;" />
                                            {{ formatSeconds(item.learningTime) }}
                                        </view>
                                        <view style="display: flex;align-items: center;color: #666666">
                                            <image src="../../static/images/time.svg"
                                                style="width: 40rpx;height: 40rpx;margin-right: 20rpx;" />
                                            {{ item.insertDate }}
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>

                        <view
                            style="display: flex; flex-direction: row; height: 80rpx; align-items: center;width: 70%;">
                            <u--input shape="circle" placeholder="请输入内容" border="surround" v-model="iptVal"
                                customStyle="width: 380rpx;margin-right:10px"></u--input>
                            <!-- <button
                        style="color:#fff; width: 64rpx; height: 64rpx; border-radius: 50%; display: flex; justify-content: center; margin-left: 20rpx; align-items: center"
                         @click="() => {
                            onSaveNotes()
                        }">
                        
                    </button> -->
                            <u-icon name="plus-circle-fill" color="#37B874" size="50rpx" @click="() => {
                                onSaveNotes()
                            }"></u-icon>
                        </view>

                    </view>
                    <image src="../../static/images/bottomIcon.svg"
                        style="width: 174rpx;height: 178rpx;position: absolute;right: 0;bottom: 0;transform: rotate(-5deg);" />
                </view>
            </view>


            <view style="margin-top: 40rpx;background-color: #fff;padding: 40rpx;">
                <view style="display: flex;justify-content: space-between;">
                    <view @click="onQueryStudyResourceNext(false)">上一视频</view>
                    <view>相关课件</view>
                    <view @click="onQueryStudyResourceNext(true)">下一视频</view>
                </view>
                <view style="margin-top: 40rpx;">
                    <view @click="() => onClickGoPlay(studentDetailItem)"
                        v-for="(studentDetailItem, index) in coursewareData">
                        <view
                            style="height: 180rpx; width: 100%; display: flex; flex-direction: row; padding: 40rpx 0;position: relative;">

                            <image style="border-radius: 6rpx; width: 180rpx; height: 180rpx; margin-right: 30rpx;"
                                :src="studentDetailItem.imageUrl"></image>
                            <view style="display: flex; flex-direction: column; justify-content: space-between;">
                                <view style="font-weight: bold;" @click="() => {
                                }">
                                    {{ studentDetailItem.name }}
                                </view>
                                <view style="display: flex; flex-direction: row; align-items: center;">
                                    <image style="width: 60rpx; height: 50rpx; margin-right: 20rpx"
                                        src="../../static/images/teacher.svg" mode="scaleToFill" />
                                    <view style="font-size: 28rpx">讲师：{{ studentDetailItem.teacher }}</view>
                                    <view
                                        style="width: 10rpx; height: 10rpx; background: #8E8E8E; border-radius: 5rpx; margin: 0 20rpx;">
                                    </view>
                                    <view style=" color: rgba(153, 153, 153, 1); font-size: 24rpx;">
                                        {{ ((studentDetailItem.learningTime || 0) / 60).toFixed(1) }}分钟</view>

                                </view>
                                <view
                                    style="display: flex; flex-direction: row; align-items: center; color: rgba(153, 153, 153, 1); font-size: 24rpx;">
                                    <view style="margin-right: 20rpx;">总时长：{{ ((studentDetailItem.time || 0) /
                                        60).toFixed(1) }}分钟
                                    </view>
                                    <view style="margin-right: 20rpx;color: #FF7D00;">
                                        进度：{{ studentDetailItem.learningTime ? parseInt(studentDetailItem.learningTime /
                                            studentDetailItem.time * 100) : 0 }}%
                                    </view>
                                </view>
                            </view>
                            <view style="position: absolute;top: 50%;right: 0;">
                                <u-icon name="arrow-right"></u-icon>
                            </view>
                        </view>

                    </view>
                </view>
            </view>
        </view>

    </view>

</template>

<script>
import { getMediaUrl, getResourceStudyNum, queryNotes, queryStudyResourceList, saveNotes, updateVideoStudyTime, queryStudyResourceNext, startPractices, resVisit, queryStudyResourceAbout } from '../../services/PracticeTestingService';
import { videoMd5Key } from '../../services/ServerService';
import md5 from "../../utils/Md5";
import { notificationFun } from '../../utils/PrjUtils';
export default {

    data() {
        return {
            queryData: {},
            playData: {},
            loginData: {},
            iptVal: '',
            studyNum: 0,
            historyTime: 0,
            efunction: false,
            videoOption: {
                isProgress: true,
            },
            note: [], //笔记
            coursewareData: [], //视频课件
            hasPlayed: false,//是否第一次播放
            sIndex: 0,
            flag: true,
            menuButtonInfo: {},
        }
    },
    onLoad(query) {
        console.log(JSON.parse(query.queryData), 'query', query)
        this.queryData = JSON.parse(query.queryData);
        console.log(this.queryData, 'dsadasd')
        this.sIndex = query.sIndex || 0
        // getSysPerson().then(cRes => {    
        //   this.loginData = {
        //     ...uni.getStorageSync('loginData'),
        //     base64: cRes.base64, 
        //     organName: cRes.organName,
        //     email: cRes.email,
        //   };
        // })
        // 获取胶囊高度
        this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()

        if (this.queryData.learningTime && this.queryData.learningTime != this.queryData.time) {
            setTimeout(() => {
                let videoContext = wx.createVideoContext('myVideo');
                this.historyTime = this.queryData.learningTime
                videoContext.seek(this.queryData.learningTime);
            }, 2000)
        }
        if (this.queryData.done) {
            this.videoOption.isProgress = false;
        }
        // this.onQueryStudyResourceList(this.queryData.outlineAlilityLevelId, this.queryData.joinId,);
        getMediaUrl({ id: this.queryData.id, outlineResourceUuid: this.queryData.outlineResourceUuid, recordUuid: this.queryData.recordUuid ? this.queryData.recordUuid : '', }).then(res => {
            this.playData = res;
            this.onGetResourceStudyNum()
            this.onqueryNotes(this.playData.recordUuid)
            this.onQueryStudyResourceList(this.queryData.outlineResourceUuid)
        })



        if (uni.getStorageSync('appKey')) {
            console.log(uni.getStorageSync('loginData'), "uni.getStorageSync('loginData')");

            this.loginData = {
                ...uni.getStorageSync('loginData'),
            };
        } else {
            this.loginData = {};
        }
        // this.onQueryNotes(this.queryData.resourceId, this.queryData.joinId);

    },

    onUnload() {
        // 页面销毁时调用
        console.log('页面销毁');
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; // 上一个页面
        prevPage.$vm.reBackData(this.sIndex);
        this.onPause();
    },
    methods: {
        goBack() {
            console.log(123);
            // uni.navigateBack({
            //     delta: 1,//返回层数，2则上上页
            // })
            this.handleUnload()

        },
        handleUnload() {
            // 页面销毁时调用
            console.log('页面销毁');
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2]; // 上一个页面
            console.log(this.sIndex, 'this.sIndex');

            prevPage.$vm.reBackData(this.sIndex);

            uni.navigateBack({
                delta: 1,//返回层数，2则上上页
            })
            this.onPause();
        },
        formatSeconds(seconds) {
            let minutes = Math.floor(seconds / 60);
            let remainingSeconds = seconds % 60;
            // 将分钟和秒数转换为字符串，并确保它们至少有两位数字
            let formattedMinutes = minutes.toString().padStart(2, '0');
            let formattedSeconds = remainingSeconds.toString().padStart(2, '0');
            return `${formattedMinutes}:${formattedSeconds}`;
        },
        onQueryStudyResourceList(outlineResourceUuid) {
            console.log(outlineResourceUuid, 'outlineResourceUuid');

            // 查询学习课件
            console.log(this.queryData, 'this.queryData', outlineResourceUuid);

            queryStudyResourceAbout({ id: this.queryData.id, uuid: this.queryData.uuid, currOutlineResourceUuid: outlineResourceUuid }).then(res => {
                this.coursewareData = res
            })
        },

        onClickSeek(time) {
            let videoContext = wx.createVideoContext('myVideo');
            this.historyTime = time
            videoContext.seek(time);
        },
        // 监听播放进度
        bindtimeupdate(e) {
            var currentTime = e.detail.currentTime; //当前进度
            var duration = e.detail.duration; //视频时长

            // // 禁止拖动进度条快进
            // if (this.videoOption.isProgress && currentTime - this.historyTime > 2) {
            //     uni.showToast({
            //         title: '不能快进哦',
            //         icon: 'none',
            //     });
            //     let videoContext = wx.createVideoContext('myVideo'); 
            //     videoContext.seek(this.historyTime);
            // }
            this.historyTime = currentTime;
        },

        onGetResourceStudyNum() {
            // 获取视频的参与学习人数
            getResourceStudyNum({ recordUuid: this.playData.recordUuid }).then(res => {
                this.studyNum = res;
            })

        },
        onqueryNotes(recordUuid) {
            // 获取笔记
            queryNotes({ recordUuid: recordUuid }).then(res => {
                this.note = res
            })
        },

        // 保存笔记
        onSaveNotes() {
            if (this.iptVal) {
                saveNotes({ recordUuid: this.playData.recordUuid, notesContent: this.iptVal, learningTime: Math.floor(this.historyTime) }).then(res => {
                    notificationFun('保存成功')
                    this.iptVal = ''
                    this.onqueryNotes(this.queryData.recordUuid)
                })
            } else {
                notificationFun('请输入笔记内容')
            }


        },
        onPause() {
            if (this.efunction) {
                return
            }

            let thisTime = this.historyTime;
            let playData = this.playData;
            if (this.historyTime === 0) {
                return;
            }
            if (thisTime + 3 > playData.duration) {
                thisTime = playData.duration * 1;
            }
            // 避免几个id加法运算
            let token;
            console.log(playData, 'playData');

            token = md5(playData.recordUuid + Math.floor(thisTime) + 'BJUPIPRACTICE')
            this.efunction = true;
            updateVideoStudyTime({ recordUuid: playData.recordUuid, time: Math.floor(thisTime), token: token }).then(res => {
                this.efunction = false;
                if (thisTime == playData.duration) {
                    this.onQueryStudyResourceList(this.playData.outlineResourceUuid);
                    this.videoOption.isProgress = false;
                    let videoContext = wx.createVideoContext('myVideo');
                    videoContext.seek(0);
                }

            });
        },
        // 第一次播放
        onPlay() {
            if (!this.hasPlayed) {
                console.log('视频第一次播放');
                resVisit({ type: 3, resourceId: this.queryData.id }).then(res => {
                    this.hasPlayed = true;
                })
            }
        },
        // 课件上一个下一个
        onQueryStudyResourceNext(value) {
            queryStudyResourceNext({ id: this.queryData.id, uuid: this.queryData.uuid, outlineResourceUuid: this.queryData.outlineResourceUuid, next: value }).then(values => {
                getMediaUrl({ id: this.queryData.id, outlineResourceUuid: values.outlineResourceUuid, recordUuid: values.recordUuid ? this.queryData.recordUuid : '', }).then(res => {
                    this.playData = res;
                    this.queryData = {
                        ...this.queryData,
                        outlineResourceUuid: values.outlineResourceUuid
                    }
                    this.onGetResourceStudyNum()

                    this.onqueryNotes(values.recordUuid)
                    this.onQueryStudyResourceList(values.outlineResourceUuid)
                })
            })
        },

        //点击课件 
        onClickGoPlay(item) {
            getMediaUrl({ id: this.queryData.id, outlineResourceUuid: item.outlineResourceUuid, recordUuid: item.recordUuid, }).then(res => {
                this.playData = res;
                this.queryData = {
                    ...this.queryData,
                    outlineResourceUuid: item.outlineResourceUuid
                }
                this.onGetResourceStudyNum()
                this.onqueryNotes(res.recordUuid)
                this.onQueryStudyResourceList(item.outlineResourceUuid)
            })
        },
        // 开始练习
        onStartPractice() {
            startPractices({ recordUuid: this.playData.recordUuid, resourceId: this.queryData.id }).then(res => {
                uni.navigateTo({
                    url: '/pages/practiceTesting/exercisesPage?practiceUuid=' + res + '&video=true' + '&id=' + this.queryData.id
                })
            })
        }
    },
}</script>